import * as THREE from 'three';
import M from './main.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
import { TWEEN } from 'three/addons/libs/tween.module.min.js';

class Test {
	constructor(books){	

		let otherFont,font,questionBoard, panel,animationID;
		const m = new M();
		const scene = new THREE.Scene();
		const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 1000 );
		const camera1 = new THREE.PerspectiveCamera( 70, 2, 0.1, 1000 );
		const fillLight1 = new THREE.HemisphereLight( 0x4488bb, 0x002244, 0.5 );
		const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
		const container = document.getElementById( 'container' );
		const renderer = new THREE.WebGLRenderer( { antialias: true } );

		init();

		async function init() {
			//载入对应语言的字体
			font = await loadFont('KaiTi');
			otherFont = await loadFont('optimer');
			//题问牌
			questionBoard = new THREE.Mesh( new THREE.PlaneGeometry(1, 0.5 ), new THREE.MeshBasicMaterial( { color: 0xffd800 } ) );
			questionBoard.position.set( 0, 0, 0.35 );
			questionBoard.rotation.y = Math.PI;
			scene.add( questionBoard );
			let text="aaaaa skjjiwe asjuiwe jkas asd huwh\n cnsjuie\n nncjshuihuic\n shc ucjiew \nwihu xc weuhdu\n ajsweuih cxewiu \n iwebsd webdy\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn\nn ";
//			let textMesh = getTextMesh(text,otherFont,0.1);
			let textMesh = getTextMesh('天人合一',font,0.2);

			questionBoard.add( textMesh );
			
			
			//场景背景设为蓝色			
			scene.background = new THREE.Color( 0x88ccee );

			//相机转动顺序
			camera.rotation.order = 'YXZ';
			camera1.rotation.order = 'YXZ';
			camera1.rotation.y = Math.PI;
			//环境光
			fillLight1.position.set( 2, 1, 1 );
			scene.add( fillLight1 );

			//带投影的光
			directionalLight.position.set( - 5, 25, - 1 );
			directionalLight.castShadow = true;
			directionalLight.shadow.camera.near = 0.01;
			directionalLight.shadow.camera.far = 500;
			directionalLight.shadow.camera.right = 30;
			directionalLight.shadow.camera.left = - 30;
			directionalLight.shadow.camera.top	= 30;
			directionalLight.shadow.camera.bottom = - 30;
			directionalLight.shadow.mapSize.width = 1024;
			directionalLight.shadow.mapSize.height = 1024;
			directionalLight.shadow.radius = 4;
			directionalLight.shadow.bias = - 0.00006;
			scene.add( directionalLight );
			//渲染器
			renderer.setPixelRatio( window.devicePixelRatio );
			renderer.setSize( window.innerWidth, window.innerHeight );
			renderer.shadowMap.enabled = true;
			renderer.shadowMap.type = THREE.VSMShadowMap;
			renderer.outputEncoding = THREE.sRGBEncoding;
			renderer.toneMapping = THREE.ACESFilmicToneMapping;
			renderer.setScissorTest(true);
			container.appendChild( renderer.domElement );
			//地面
			const gt = new THREE.TextureLoader().load( m.current()+'floor.jpg' );
			gt.wrapS = gt.wrapT = THREE.RepeatWrapping; 
			gt.repeat.set(10, 15); 
			const gm = new THREE.MeshPhongMaterial( { color: 0xffffff, map: gt } );
			const ground = new THREE.Mesh( new THREE.BoxGeometry( 200, 1, 200, 1, 1, 1 ), gm );
			ground.position.set(0,-10,0);
			scene.add(ground);
			
			window.addEventListener( 'resize', onWindowResize );
			animate();
		}
		function getTextBox(text,font,size){
			//该方法效率极低，主要是生成TextGeometry费时太久
			//可替代的方案是根据字体文件中每个字符的尺寸来进行计算，
			//但是不知道字符间距是怎么定义的总是算不准，因此暂时搁置
			let box = new TextGeometry( text, {
				font: font,
				size: size,
				height: 0,
			} );
			//计算边界
			box.computeBoundingBox();
			return {w:box.boundingBox.max.x-box.boundingBox.min.x, h:box.boundingBox.max.y-box.boundingBox.min.y};		
		}
		function getTextMesh(otext,font,osize){
			let text = otext;
			let size = osize;
			while(true){
				//获取边界
				let box = getTextBox(text,font,size);
				if (box.h>0.495){
					//超高
					//字体太小了就将下面的部分截断，用省略号代替
					if (size-0.005 <= 0.02) {
						let lines = text.split('\n');
						let l = Math.floor(lines.length * (0.5 / box.h));
						text = "";
						for(let i=0;i<l;i++) text += lines[i]+(i==l-1?"...":"")+'\n';
						break;
					}else{
						//重新进行换行处理
						size -= 0.005;
						text = otext;
					}
				}else if (box.w>0.99) {
					//超宽
					let newText="";
					let lines = text.split('\n');
					//找出最宽的行
					let max = 0;
					for(let i=0;i<lines.length;i++){
						if (max<lines[i].length) max = lines[i].length;
					}
					//每行最多几个字母
					//TODO：没有考虑字母不同宽，以及中英文混合的问题
					let lc = Math.floor(0.99/(box.w/max));
					//逐行处理
					for(let i=0;i<lines.length;i++){
						//该行超宽
						if (lines[i].length>lc){
							//应该分几行
							let l = Math.ceil(lines[i].length/lc);
							if (font.data.familyName=="KaiTi"){
								//中文的换行处理
								//TODO日文的处理以及中英文混合的情况
								for(let j=0;j<l;j++){
									newText += lines[i].substr(j*lc,lc)+"\n";
								}
							}else{
								//其他语言的换行处理
								//TODO：字母不等距和没有空格的情况
								let words = lines[i].split(' ');
								let c = 0;
								for(let j=0;j<words.length;j++){
									newText += words[j]+" ";
									c+=words.length;
									if (j<words.length-1 && c+words[j+1].length>lc){
										//再加一个词就超宽时换行
										newText +="\n"
										c=0;
									}
								}
							}
						}else newText +=lines[i]+"\n";
					}
					text = newText;
				}else break;
			}
			const textGeo = new TextGeometry( text, {
				font: font,
				size: size,
				height: 0,
			} );
			//自动居中
			textGeo.center();
			return new THREE.Mesh( textGeo, new THREE.MeshBasicMaterial( { color: 0x000000 } ) );
		}
		async function loadFont(font) {
			const p = await new Promise((resolve)=>{				
				const loader = new FontLoader();
				loader.load( m.current()+font+'.json', resolve );
		  });
		  return p;
		}
		function onWindowResize() {

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();

			renderer.setSize( window.innerWidth, window.innerHeight );

			render();

		}

		function animate() {

			animationID = requestAnimationFrame( animate );
			render();

		}

		function render() {
			let width = window.innerWidth;
			let height = window.innerHeight;
		  renderer.setScissor(0, 0, width, height);
		  renderer.setViewport(0, 0, width, height);
		  renderer.render(scene, camera);

		  // 右下角剪裁区
		  renderer.setScissor((width-height / 3*2)/2, height / 12, height / 3*2, height / 3);
		  renderer.setViewport((width-height / 3*2)/2, height / 12, height / 3*2, height / 3);
		  renderer.render(scene, camera1);

		}
	}
}
export { Test };